package com.gobo.eduservice.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.gobo.commonutils.R;
import com.gobo.eduservice.clients.AliyunOssClient;
import com.gobo.eduservice.clients.OrderServiceClient;
import com.gobo.eduservice.pojo.EduChapter;
import com.gobo.eduservice.pojo.EduCourse;
import com.gobo.eduservice.mapper.EduCourseMapper;
import com.gobo.eduservice.pojo.EduCourseDescription;
import com.gobo.eduservice.pojo.EduVideo;
import com.gobo.eduservice.pojo.chapter.ChapterVo;
import com.gobo.eduservice.pojo.front.FrontCourseInfoVo;
import com.gobo.eduservice.pojo.front.FrontCourseQuery;
import com.gobo.eduservice.pojo.vo.CourseInfo;
import com.gobo.eduservice.pojo.vo.CoursePublishVo;
import com.gobo.eduservice.pojo.vo.EduCourseQuery;
import com.gobo.eduservice.service.EduChapterService;
import com.gobo.eduservice.service.EduCourseDescriptionService;
import com.gobo.eduservice.service.EduCourseService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gobo.eduservice.service.EduVideoService;
import com.gobo.servicebase.handler.exception.pojo.GoboException;
import com.gobo.servicebase.vo.CourseInfoFormVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 课程 服务实现类
 * </p>
 *
 * @author gobo-generator
 * @since 2021-09-19
 */
@Service
public class EduCourseServiceImpl extends ServiceImpl<EduCourseMapper, EduCourse> implements EduCourseService {

    @Autowired
    private EduCourseDescriptionService descriptionService;

    @Autowired
    private EduVideoService videoService;

    @Autowired
    private EduChapterService chapterService;

    @Autowired
    private AliyunOssClient ossClient;

    @Autowired
    private OrderServiceClient orderServiceClient;

    @CacheEvict(value = "course", key = "'selectIndexEightCourses'")
    @Override
    public String saveCourseAndDescription(CourseInfo courseInfo) {
        EduCourse eduCourse = new EduCourse();
        EduCourseDescription courseDescription = new EduCourseDescription();
        BeanUtils.copyProperties(courseInfo, eduCourse);

        int insert = baseMapper.insert(eduCourse);
        if (insert < 1) {
            throw new GoboException(50005, "插入课程信息异常！后端500");
        }
        String id = eduCourse.getId();
        BeanUtils.copyProperties(courseInfo, courseDescription);
        courseDescription.setId(id);
        boolean isave = descriptionService.save(courseDescription);
        return isave ? id : null;
    }

    @Override
    public CourseInfo getCourseInfoById(String courseId) {
        //TODO
        EduCourse eduCourse = baseMapper.selectById(courseId);
        CourseInfo courseInfo = new CourseInfo();
        BeanUtils.copyProperties(eduCourse, courseInfo);
        EduCourseDescription description = descriptionService.getById(courseId);
        courseInfo.setDescription(description.getDescription());
        return courseInfo;
    }

    @CacheEvict(value = "course", key = "'selectIndexEightCourses'")
    @Override
    public String updateCourseInfoById(CourseInfo courseInfo) {
        EduCourse eduCourse = new EduCourse();
        EduCourseDescription courseDescription = new EduCourseDescription();
        BeanUtils.copyProperties(courseInfo, eduCourse);
        int result = baseMapper.updateById(eduCourse);
        if (result < 1) {
            throw new GoboException(50005, "更新课程基本信息异常！后端500");
        }
        String id = eduCourse.getId();
        BeanUtils.copyProperties(courseInfo, courseDescription);
        courseDescription.setId(id);
        boolean idUpdate = descriptionService.updateById(courseDescription);
        return idUpdate ? id : null;
    }

    @Override
    public CoursePublishVo getCoursePublishVo(String courseId) {
        CoursePublishVo coursePublishVo = baseMapper.selectCoursePublishVoById(courseId);
        return coursePublishVo;
    }

    @Override
    public void pageQuery(Page<EduCourse> pageParam, EduCourseQuery eduCourseQuery) {
        QueryWrapper<EduCourse> queryWrapper = new QueryWrapper<>();
        String title = eduCourseQuery.getTitle();
        if (!StringUtils.isEmpty(title)) {
            queryWrapper.like("title", title);
        }
        if (!StringUtils.isEmpty(eduCourseQuery.getTeacherId())) {
            queryWrapper.eq("teacher_id", eduCourseQuery.getTeacherId());
        }
        if (!StringUtils.isEmpty(eduCourseQuery.getSubjectId())) {
            queryWrapper.eq("subject_id", eduCourseQuery.getSubjectId());
        }
        if (!StringUtils.isEmpty(eduCourseQuery.getSubjectParentId())) {
            queryWrapper.eq("subject_parent_id", eduCourseQuery.getSubjectParentId());
        }
        if (!StringUtils.isEmpty(eduCourseQuery.getStatus())) {
            queryWrapper.eq("status", eduCourseQuery.getStatus());
        }
        baseMapper.selectPage(pageParam, queryWrapper);
    }

    @CacheEvict(value = "course", key = "'selectIndexEightCourses'")
    @Override
    public Boolean removeCourseByCourseId(String courseId) {
        //删除小节

        boolean remove = videoService.removeVideoAndSourceByCourseId(courseId);
        //删除章节
        QueryWrapper<EduChapter> queryWrapper2 = new QueryWrapper<>();
        queryWrapper2.eq("course_id", courseId);
        boolean remove2 = chapterService.remove(queryWrapper2);
        //删除描述
        boolean b = descriptionService.removeById(courseId);
        //删除Oss中的封面
        EduCourse eduCourse = baseMapper.selectById(courseId);
        String cover = eduCourse.getCover();
        ossClient.removeFile(cover);
        //删除详情
        int i = baseMapper.deleteById(courseId);

        return i == 1;
    }

    @Cacheable(value = "course", key = "'selectIndexEightCourses'")
    @Override
    public List<EduCourse> getIndexCourses() {
        QueryWrapper<EduCourse> wrapper = new QueryWrapper<>();
        wrapper.orderByDesc("view_count");
        wrapper.last("limit 8");
        return baseMapper.selectList(wrapper);
    }

    @Override
    public List<EduCourse> getFrontCourseByTeacherId(String id) {
        QueryWrapper<EduCourse> queryWrapper = new QueryWrapper<>();
        queryWrapper.orderByAsc("view_count");
        queryWrapper.eq("teacher_id", id);
        queryWrapper.eq("status", "Normal");
        List<EduCourse> courseList = baseMapper.selectList(queryWrapper);
        return courseList;
    }

    @Override
    public Map<String, Object> getFrontCourseByCourseCourseQuery(Page<EduCourse> page, FrontCourseQuery courseQuery) {
        QueryWrapper<EduCourse> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("status", "Normal");
        if (courseQuery != null) {

            if (!StringUtils.isEmpty(courseQuery.getSubjectParentId())) {
                queryWrapper.eq("subject_parent_id", courseQuery.getSubjectParentId());
            }

            if (!StringUtils.isEmpty(courseQuery.getSubjectId())) {
                queryWrapper.eq("subject_id", courseQuery.getSubjectId());
            }

            if (!StringUtils.isEmpty(courseQuery.getBuyCountSort())) {
                queryWrapper.orderByDesc("buy_count");
            }

            if (!StringUtils.isEmpty(courseQuery.getGmtCreateSort())) {
                queryWrapper.orderByDesc("gmt_create");
            }

            if (!StringUtils.isEmpty(courseQuery.getPriceSort())) {
                queryWrapper.orderByDesc("price");
            }
        }
        baseMapper.selectPage(page, queryWrapper);
        List<EduCourse> records = page.getRecords();
        long current = page.getCurrent();
        long pages = page.getPages();
        long size = page.getSize();
        long total = page.getTotal();
        boolean hasNext = page.hasNext();
        boolean hasPrevious = page.hasPrevious();

        Map<String, Object> map = new HashMap<String, Object>();
        map.put("items", records);
        map.put("current", current);
        map.put("pages", pages);
        map.put("size", size);
        map.put("total", total);
        map.put("hasNext", hasNext);
        map.put("hasPrevious", hasPrevious);

        return map;
    }

    @Override
    public R getFrontCourseInfoById(String id,String memberId) {
        //获取课程基本信息 FrontCourseInfoVo
        FrontCourseInfoVo frontCourseInfoVo =  baseMapper.selectFrontCourseInfoVoById(id);
        //获取章节以及小节
        List<ChapterVo> chapterVoList = chapterService.getChapterVoList(id);
        if (StringUtils.isEmpty(memberId)){
            return R.error();
        }

        boolean isBuyCourse = orderServiceClient.getOrderStatusByCourseIdAndMemberId(id, memberId);

        return R.ok().data("courseInfo",frontCourseInfoVo).data("chapterVoList",chapterVoList).data("isbuyCourse",isBuyCourse);
    }

    @Override
    public CourseInfoFormVo getCommonCourseInfoFormVo(String id) {
        //获取课程基本信息 FrontCourseInfoVo
        FrontCourseInfoVo frontCourseInfoVo =  baseMapper.selectFrontCourseInfoVoById(id);
        CourseInfoFormVo courseInfoFormVo = new CourseInfoFormVo();
        BeanUtils.copyProperties(frontCourseInfoVo,courseInfoFormVo);
        return courseInfoFormVo;
    }
}
